#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    this->indexed_tab = 0;
    this->tab_number = 1;
    this->is_first_tab = false;

    ui->setupUi(this);
    ui->dockCodingHelp->setVisible( false );
    ui->dockCompileOutput->setVisible( false );

    ui->tabComponent->setTabsClosable( true );
    ui->tabComponent->removeTab( 1 );

    ui->tabComponent->setTabText( indexed_tab , "---");
    ui->tabComponent->setTabIcon(indexed_tab, QIcon("images/vipera_document.png"));

    this->openedFiles = new QStringList();

    //Pulisco il vector di informazioni relative al file aperto
    script_info.clear();

    //Connection between actions and docks
    connect(ui->actionOutput, SIGNAL(triggered(bool)), this, SLOT(onDockOutput(bool)));
    connect(ui->actionCoding_Help, SIGNAL(triggered(bool)),this,SLOT(onDockCompileHelp(bool)));
    connect(ui->actionOpen,SIGNAL(triggered(bool)),this,SLOT(onOpenFile()));
    connect(ui->actionQuit,SIGNAL(triggered(bool)),this,SLOT(onQuit()));
    connect(ui->actionAbout, SIGNAL(triggered()),this,SLOT(onAbout()));
    connect(ui->action2_6, SIGNAL(triggered(bool)),this,SLOT(on26Version(bool)));
    connect(ui->action3_1, SIGNAL(triggered(bool)),this,SLOT(on31Version(bool)));
    connect(ui->tabComponent, SIGNAL(tabCloseRequested(int)),this,SLOT(onTabCloseRequest(int)));
    connect(ui->actionRun, SIGNAL(triggered()),this,SLOT(onRunProgram()));

    this->file_selection_dialog = new QFileDialog(this);

    this->file_selection_dialog->setFileMode(QFileDialog::AnyFile);
    this->file_selection_dialog->setNameFilter(tr("Python (*.py)"));
    this->file_selection_dialog->setViewMode(QFileDialog::Detail);

    this->about_dialog = new AboutDialog(this);
    this->about_dialog->setVisible( false );
    this->save_dialog = new closetabdialog(this);
    this->save_dialog->setVisible(false);

    connect(save_dialog,SIGNAL(pubOk()),this,SLOT(subSaveClosingTab()));
    connect(save_dialog,SIGNAL(pubCancel()),this,SLOT(subDiscardClosingTab()));

    ui->action2_6->setChecked(true);
    this->isV26Used = true;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onDockOutput(bool checked)
{

    ui->dockCompileOutput->setVisible( checked );
}

void MainWindow::onDockCompileHelp(bool checked)
{
   ui->dockCodingHelp->setVisible( checked );
}

void MainWindow::closeEvent(QCloseEvent * event)
{
   this->closeOperation();
}

//Slots file menu
void MainWindow::onOpenFile()
{
    /*Approccio con puntatori*/
    if (this->file_selection_dialog->exec())
    {
        fileNames = this->file_selection_dialog->selectedFiles();
        this->loadFiles();
    }
   /* QStringList fileName;
    fileName = QFileDialog::getOpenFileNames(this,
     tr("Open Source File"), "~/", tr("Python Files (*.py)"));*/

}

void MainWindow::onSaveFile()
{
}

void MainWindow::onSaveAllFile()
{
}

void MainWindow::onClose()
{
}

void MainWindow::onCloseAll()
{
}

void MainWindow::onCloseAllButMe()
{
}

void MainWindow::onQuit()
{
    this->closeOperation();
}

void MainWindow::onAbout()
{
    this->about_dialog->setVisible( true );
}

void MainWindow::onTabCloseRequest(int index)
{
    qDebug("Richiesta chiusura tab %d",index);
    QString msg_to_send = ui->tabComponent->tabText(ui->tabComponent->currentIndex());
    qDebug("File da salvare: %s",msg_to_send.toStdString().c_str());
    this->save_dialog->setMessage("Salvare file: "+ msg_to_send + "?");
    this->save_dialog->setVisible(true);
    this->closing_tab = ui->tabComponent->currentIndex();
}

void MainWindow::closeOperation()
{
   qDebug("Chiusura programma.");
   exit(0);
}

void MainWindow::loadFiles()
{
    qDebug("is_first_tab %d",is_first_tab);
    if( !is_first_tab )
    {
        //Carico il primo programma
        QFile file(fileNames.at(0) );
        if(file.open(QFile::ReadWrite | QFile::Text))
        {
            ui->txtCode->setPlainText(file.readAll());

            //Inserisco le informazioni per l'IDE nell'apposita struttura
            ScriptEditInfo infos;
            infos.fullPath = file.fileName();
            infos.editor_ptr = ui->txtCode;
            script_info.push_back(infos);
        }
        QStringList fileName_sl = file.fileName().split("/");
        this->openedFiles->push_back(file.fileName());
        ui->tabComponent->setTabText(this->indexed_tab, fileName_sl.at(fileName_sl.size()-1));

        is_first_tab = true;

    }
    else
    {
        QFile file(fileNames.at(0) );
        QStringList fileName_sl = file.fileName().split("/");
        //Creo un nuovo tab
        QWidget * page = new QWidget(this);
        int new_tab_id = ui->tabComponent->addTab(page,QIcon("./images/vipera_document.png"),fileName_sl.at(fileName_sl.size()-1));

        this->indexed_tab = ui->tabComponent->size().height();
        qDebug("%d",this->indexed_tab);
        this->indexed_tab = ui->tabComponent->size().width();
        qDebug("%d",this->indexed_tab);

        if(file.open(QFile::ReadWrite | QFile::Text))
        {
            //ui->tabComponent->settab->setPlainText(file.readAll());

            QWidget * nTab = ui->tabComponent->widget(new_tab_id);
            QGridLayout * gridLayout_2;
            QTextBrowser * txtCode;
            nTab->setObjectName(QString("nTab")+QString::number(new_tab_id));
            gridLayout_2 = new QGridLayout(nTab);
            gridLayout_2->setSpacing(6);
            gridLayout_2->setMargin(11);
            gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2")+QString::number(new_tab_id));
            txtCode = new QTextBrowser(nTab);
            txtCode->setObjectName(QString::fromUtf8("txtCode")+QString::number(new_tab_id));
            QFont font;
            font.setFamily(QString::fromUtf8("Monospace"));
            font.setPointSize(8);
            txtCode->setFont(font);
            txtCode->viewport()->setProperty("cursor", QVariant(QCursor(Qt::IBeamCursor)));
            txtCode->setMidLineWidth(1);
            txtCode->setReadOnly(false);

            gridLayout_2->addWidget(txtCode, 0, 0, 1, 1);
            txtCode->setPlainText(file.readAll());

            this->openedFiles->push_back(file.fileName());

            QStringList fileName_sl = file.fileName().split("/");
            ui->tabComponent->setTabText(new_tab_id, fileName_sl.at(fileName_sl.size()-1));

            //Inserisco le informazioni per l'IDE nell'apposita struttura
            ScriptEditInfo infos;
            infos.fullPath = file.fileName();
            infos.editor_ptr = txtCode;
            script_info.push_back(infos);
        }
    }

}

void MainWindow::on26Version(bool checked)
{
    if(checked)
    {
        this->isV26Used = true;
        ui->action3_1->setChecked(false);
        ui->statusBar->showMessage(QString("Versione impostata 2.6."),15000);
    }
    else
    {
        //Non posso dececkare senza selezionare l'altra opzione.
        ui->action2_6->setChecked(true);
    }
}

void MainWindow::on31Version(bool checked)
{
    if(checked)
    {
        this->isV26Used = false;
        ui->action2_6->setChecked(false);
        ui->statusBar->showMessage(QString("Versione impostata 3.1."),15000);
    }
    else
    {
        //Non posso dececkare senza selezionare l'altra opzione
        ui->action3_1->setChecked(true);
    }
}

void MainWindow::subSaveClosingTab()
{
    qDebug("Ricevuto segnale di salvataggio tab %d.",closing_tab);

    ScriptEditInfo infos = script_info.at(closing_tab);

    QString textToSave = infos.editor_ptr->toPlainText();

    QFile file(openedFiles->at(closing_tab));

    if(file.open(QFile::ReadWrite | QFile::Text))
    {
        QByteArray ba (textToSave.toStdString().c_str());
        file.write(ba);
    }
    file.close();

    //Distruggo il tab.
    ui->tabComponent->removeTab(closing_tab);
}

void MainWindow::subDiscardClosingTab()
{
    qDebug("Ricevuto segnali di discard delle modifiche.");
}


void MainWindow::onRunProgram()
{
    if(!is_first_tab)
        return;
    QString fn = this->fileNames.at(ui->tabComponent->currentIndex());
    qDebug("Richiesta l'esecuzione del file %s",fn.toStdString().c_str());

    if(this->isV26Used)
    {
        QString runCommand = "python "+fn;
        qDebug("Comando shell: %s",runCommand.toStdString().c_str());
        int result = system(runCommand.toStdString().c_str());
    }
    else
    {
        QString runCommand = "python3 "+fn;
        qDebug("Comando shell: %s",runCommand.toStdString().c_str());
        int result = system(runCommand.toStdString().c_str());
    }
}
